package com.syni.mdd.sjb.tool.utils;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.syni.mdd.sjb.tool.config.SmsConfig;
import lombok.extern.log4j.Log4j2;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @className SmsUtils
 * @description TOO
 * @Author cfx
 * @DATE 2019/6/22 8:48
 * @VERSION 1.0
 **/
@Log4j2
@Component
@EnableConfigurationProperties(SmsConfig.class)
public class SmsUtils {
    private final static String CHINA_CODE = "86";

    @Autowired
    SmsConfig smsConfig;

    public boolean sendSmsVerificationCode(Integer channel,String phone,String verificationCode) {
        boolean result = false;
        try {
            String appId = smsConfig.getAppId();
            String appKey = smsConfig.getAppKey();
            Integer templateId = Integer.parseInt(smsConfig.getSjbTemplateId());
            SmsSingleSender ssender = new SmsSingleSender(Integer.parseInt(appId),appKey);
            String[] params = {verificationCode};
            SmsSingleSenderResult senderResult = ssender.sendWithParam(CHINA_CODE, phone,
                    templateId, params, smsConfig.getSjbSign(), "", "");  // 签名参数未提供或者为空时，会使用默认签名发送短信
            result = senderResult.result == 1 ? true : false;
        } catch (HTTPException e) {
            // HTTP 响应码错误
            log.error(e.getMessage(),e);
        } catch (JSONException e) {
            // JSON 解析错误
            log.error(e.getMessage(),e);
        } catch (IOException e) {
            // 网络 IO 错误
            log.error(e.getMessage(),e);
        }
        return result;
    }
}
